<template>
    <div class="layout-route">
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <!-- <el-form-item label="产品名称" prop="product_name">
                    <el-input v-model.trim="queryParams.product_name" placeholder="请输入产品名称" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item> -->
                <el-form-item label="分类" prop="product_attr_id">
                    <el-select v-model="queryParams.product_attr_id" placeholder="请选择分类" clearable style="width: 240px">
                        <el-option v-for="(dict, index) in dict.attrList" :key="index" :label="dict.type_name" :value="dict.type_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="采购类型" prop="purchase_type">
                    <el-select v-model="queryParams.purchase_type" placeholder="请选择采购类型" clearable style="width: 240px">
                        <el-option v-for="(dict, index) in dict.purchaseTypeList" :key="index" :label="dict.label" :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商" prop="supply_id">
                    <!-- <el-select v-model="queryParams.supply_id" placeholder="请选择供应商" clearable style="width: 240px"  popper-class="custom-select">
                        <el-option v-for="(dict, index) in dict.supplyList" :key="index" :label="dict.supply_name" :value="dict.id"></el-option>
                    </el-select> -->
                    <SelectPage
                        v-model="queryParams.supply_id"
                        placeholder="请选择供应商"
                        :url="$api.supply.getSupplyList"
                        show_field="supply_name"
                        query_field="supply_name"
                        query_field2="spu"
                        filterable
                        clearable
                        popper-class="custom-select"
                        style="width: 240px"
                    ></SelectPage>
                </el-form-item>
                <el-form-item label="SPU" prop="spu">
                    <el-input v-model.trim="queryParams.spu" placeholder="请输入SPU" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="产品标签" prop="product_tag">
                    <el-radio-group v-model="queryParams.product_tag" @change="changeCustomDate" style="width: 240px">
                        <el-radio-button v-for="(dict, index) in dict.productTagList" :key="index" :label="dict.value">{{ dict.label }}</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="产品状态" prop="product_status">
                    <el-select v-model="queryParams.product_status" placeholder="请选择产品状态" clearable style="width: 240px">
                        <el-option v-for="(dict, index) in dict.productStatus" :key="index" :label="dict.label" :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上架时间" prop="published_time">
                    <el-date-picker v-model="queryParams.published_time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="开发类型" prop="develop_type">
                    <el-select v-model="queryParams.develop_type" placeholder="请选择开发类型" clearable style="width: 240px">
                        <el-option v-for="(dict, index) in dict.developTypeList" :key="index" :label="dict.label" :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="销量时间" prop="customDate">
                    <el-radio-group v-model="queryParams.customDate" @change="changeCustomDate" style="width: 240px">
                        <el-radio-button v-for="(dict, index) in dict.customDateList" :key="index" :label="dict.value">{{ dict.label }}</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="el-icon-plus" @click="showProductDialog({}, 'add')">添加</el-button>
                </el-col>
                <!-- <el-col :span="1.5">
                    <el-button type="warning" plain @click="downloadExcel">下载模板</el-button>
                </el-col> -->
                <el-col :span="1.5">
                    <!-- <upload-button :action="action" @complete="getList"></upload-button> -->
                    <upload-product @update="getList"></upload-product>
                </el-col>
                <el-col :span="1.5" v-if="showExportButton">
                    <el-button type="warning" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table v-loading="loading" :data="tableData" row-key="id" border script @sort-change="handleSortChange">
                <!-- <el-table-column label="产品大类" prop="product_type_1" min-width="140" v-if="showColumn('product_type_1')"></el-table-column> -->
                <el-table-column label="分类" prop="product_attr_type_value" min-width="140" v-if="showColumn('product_attr_type_value')"></el-table-column>
                <el-table-column label="SPU" prop="spu" min-width="120" v-if="showColumn('spu')">
                    <template slot-scope="scope">
                        <el-link type="primary" @click="showSpuListDialog(scope.row)">{{ scope.row.spu }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="产品图片" min-width="100" v-if="showColumn('product_images_arr')">
                    <template slot-scope="scope">
                        <ImageUploadImg v-model="scope.row.product_images_arr" :readOnly="true"></ImageUploadImg>
                    </template>
                </el-table-column>
                <el-table-column :label="customDateLabel" prop="spu_30days" min-width="120" sortable="custom" :sort-orders="['descending', 'ascending']" v-if="showColumn('spu_30days')">
                    <template slot-scope="scope">
                        {{ scope.row[customDateKey] || scope.row.spu_30days }}
                    </template>
                </el-table-column>
                <el-table-column label="产品名称" prop="product_name" min-width="220" show-overflow-tooltip v-if="showColumn('product_name')"></el-table-column>
                <el-table-column label="产品标签" prop="product_tag" min-width="100" show-overflow-tooltip v-if="showColumn('product_tag')">
                    <!-- <template slot-scope="scope">
                        {{ formateProductTag(scope.row.product_tag) }}
                    </template> -->
                </el-table-column>
                <el-table-column label="昨日增长率" prop="GrowthRate" min-width="100" v-if="showColumn('GrowthRate')"></el-table-column>
                <el-table-column label="最大重量" prop="max_weight" min-width="100" v-if="showColumn('max_weight')"></el-table-column>
                <el-table-column label="最小重量" prop="min_weight" min-width="100" v-if="showColumn('min_weight')"></el-table-column>
                <el-table-column label="平均重量" prop="average_weight" min-width="100" v-if="showColumn('average_weight')"></el-table-column>

                <el-table-column label="产品尺码图片" min-width="100" v-if="showColumn('product_size_images_arr')">
                    <template slot-scope="scope">
                        <ImageUploadImg v-model="scope.row.product_size_images_arr" :readOnly="true"></ImageUploadImg>
                    </template>
                </el-table-column>
                <el-table-column label="商品尺码" prop="size_variant" min-width="160" show-overflow-tooltip v-if="showColumn('size_variant')"></el-table-column>
                <el-table-column label="商品颜色" prop="color_variant" min-width="240" show-overflow-tooltip v-if="showColumn('color_variant')"></el-table-column>
                <el-table-column label="面料成分" prop="fabric_content" min-width="240" show-overflow-tooltip v-if="showColumn('fabric_content')"></el-table-column>
                <el-table-column label="采购成本" prop="purchase_cost" min-width="120" v-if="showColumn('purchase_cost')"></el-table-column>
                <el-table-column label="采购类型" min-width="120" v-if="showColumn('purchase_type')">
                    <template slot-scope="scope">
                        {{ scope.row.purchase_type | formatLabelByValueFuzzy(dict.purchaseTypeList) }}
                    </template>
                </el-table-column>
                <el-table-column label="开发类型" min-width="100" v-if="showColumn('develop_type')">
                    <template slot-scope="scope">
                        {{ scope.row.develop_type | formatLabelByValueFuzzy(dict.developTypeList) }}
                    </template>
                </el-table-column>

                <el-table-column label="供应商" prop="supply_links" min-width="300" class-name="border-cell" v-if="showColumn('supply_links')">
                    <template slot-scope="scope" v-if="scope.row.supply_links.length > 0">
                        <div v-for="(item, index) in scope.row.supply_links" :key="index" class="border-cell-item">
                            <el-tooltip effect="dark" :content="item.supply_link" placement="top">
                                <el-link type="primary" @click="toSupply(item.supply_link)">{{ item.supply_name }}</el-link>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="产品状态" min-width="100" v-if="showColumn('product_status')">
                    <template slot-scope="scope">
                        {{ scope.row.product_status | formatLabelByValueFuzzy(dict.productStatus) }}
                    </template>
                </el-table-column>
                <el-table-column label="运营者" prop="develper" min-width="100" v-if="showColumn('develper')"></el-table-column>
                <el-table-column label="上架时间" prop="published_time" min-width="160" v-if="showColumn('published_time')"></el-table-column>
                <el-table-column label="操作" width="240" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-plus" @click="showSkuDialog(scope.row, 'add')">sku添加</el-button>
                        <!-- <el-button type="text" icon="el-icon-search" @click="showProductDialog(scope.row, 'view')">详情</el-button> -->
                        <el-button type="text" icon="el-icon-edit" @click="showProductDialog(scope.row, 'edit')">编辑</el-button>
                        <el-button type="text" icon="el-icon-edit" @click="deleteItemP(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" />
        </div>
        <product-dialog v-model="productDialog.visible" v-if="productDialog.visible" :params="productDialog.data" :type="productDialog.type" @success="handleQuery2"></product-dialog>
        <sku-dialog v-model="skuDialog.visible" v-if="skuDialog.visible" :params="skuDialog.data" :type="skuDialog.type" @success="handleQuery"></sku-dialog>
        <spu-list-dialog v-model="spuListDialog.visible" v-if="spuListDialog.visible" :params="spuListDialog.data"></spu-list-dialog>
    </div>
</template>
<script>
import { queryProductList, getAttrList, getPurchaseLevel, exportProduct, deleteItemP, getDevelopType, getProductTag, getSoleType } from '@/api/product'
import { getSupplyList } from '@/api/supply'
import ProductDialog from '../components/ProductDialog.vue'
import SkuDialog from '../components/ProductSkuDialog.vue'
import SpuListDialog from '../components/ProductSpuListDialog.vue'

import UploadProduct from '../components/UploadProduct.vue'
import { exportFile } from '@/utils/index'
import { parseTime } from '@/utils/quickadmin'
import { PRODUCT_STATUS } from '../constant'
export default {
    name: 'ProductInfoList',
    components: { ProductDialog, SkuDialog, SpuListDialog, UploadProduct },
    data() {
        return {
            action: process.env.VUE_APP_BASE_API + '/product/product/importInfo',
            downloadUrl: process.env.VUE_APP_BASE_API + '/storage/system/template/product.xlsx',
            // 遮罩层
            loading: true,
            download: false,
            // 选中数组
            ids: [],
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            showExportButton: true,
            // 状态数据字典

            dict: {
                customDateList: [
                    { label: '3天', value: 1, key: 'spu_3days' },
                    { label: '7天', value: 2, key: 'spu_7days' },
                    { label: '30天', value: 3, key: 'spu_30days' },
                ],
                developTypeList: [],
                purchaseTypeList: [],
                attrList: [],
                supplyList: [],
                productStatus: PRODUCT_STATUS,
                productTagList: [
                    { label: '新品', value: 1 },
                    { label: '热卖', value: 2 },
                ],
            },
            supplyList: [],
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                customDate: 3,
                product_tag: undefined,
                product_name: undefined,
                spu: undefined,
                product_attr_id: undefined,
                purchase_type: undefined,
                supply_id: undefined,
                published_time: [],
                product_status: undefined,
                handleSortChange: undefined,
            },
            productDialog: {
                visible: false,
                data: {},
                type: '',
            },
            skuDialog: {
                visible: false,
                data: {},
                type: '',
            },
            spuListDialog: {
                visible: false,
                data: {},
            },
            columns: [
                // {label:'产品大类', prop: 'product_type_1', visible: true },
                { id: 1, label: '分类', prop: 'product_attr_type_value', visible: true },
                { id: 2, label: 'SPU', prop: 'spu', visible: true },
                { id: 3, label: '近30天销量', prop: 'spu_30days', visible: true },
                { id: 4, label: '产品名称', prop: 'product_name', visible: true },
                { id: 5, label: '产品标签', prop: 'product_tag', visible: true },
                { id: 6, label: '昨日增长率', prop: 'GrowthRate', visible: true },
                { id: 6, label: '最大重量', prop: 'max_weight', visible: true },
                { id: 7, label: '最小重量', prop: 'min_weight', visible: true },
                { id: 8, label: '平均重量', prop: 'average_weight', visible: true },
                { id: 9, label: '产品图片', prop: 'product_images_arr', visible: true },
                { id: 10, label: '产品尺码图片', prop: 'product_size_images_arr', visible: true },
                { id: 11, label: '商品尺码', prop: 'size_variant', visible: true },
                { id: 12, label: '商品颜色', prop: 'color_variant', visible: true },
                { id: 13, label: '面料成分', prop: 'fabric_content', visible: true },
                { id: 14, label: '采购成本', prop: 'purchase_cost', visible: true },
                { id: 15, label: '采购类型', prop: 'purchase_type', visible: true },
                { id: 16, label: '供应商', prop: 'supply_links', visible: true },
                { id: 17, label: '产品状态', prop: 'product_status', visible: true },
                { id: 18, label: '运营者', prop: 'develper', visible: true },
                { id: 19, label: '上架时间', prop: 'published_time', visible: true },
            ],
        }
    },
    computed: {
        customDateLabel() {
            const label = this.dict.customDateList?.find(item => item.value == this.queryParams.customDate)?.label ?? '30天'
            return `近${label}销量`
        },
        customDateKey() {
            return this.dict.customDateList?.find(item => item.value == this.queryParams.customDate)?.key ?? 'spu_30days'
        },
    },
    async created() {
        this.loading = true
        try {
            const [soleTypeData, attrData, purchaseLevelData, supplyData, developTypeData, productTagData] = await Promise.all([
                getSoleType(),
                getAttrList(),
                getPurchaseLevel(),
                getSupplyList(),
                getDevelopType(),
                getProductTag(),
            ])
            this.showExportButton = soleTypeData?.data != 1 ?? 0
            this.dict.attrList = attrData?.data ?? []
            this.dict.purchaseTypeList = purchaseLevelData?.data ?? []
            this.dict.supplyList = supplyData?.data ?? []
            this.dict.developTypeList = developTypeData?.data ?? []
            this.dict.productTagList = productTagData?.data ?? []
        } catch (error) {
            this.loading = false
        }
        this.getList()
    },
    methods: {
        formateProductTag(values) {
            if (!values) {
                return ''
            }
            const valueList = values.split(',')
            let tags = []
            this.dict.productTagList.forEach(item => {
                valueList.forEach(value => {
                    if (value == item.value) {
                        tags.push(item.label)
                    }
                })
            })
            return tags.join(',')
        },
        changeCustomDate() {
            this.handleQuery()
        },
        deleteItemP(row) {
            this.$confirm(`是否确认删除?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    deleteItemP({ id: row.id }).then(res => {
                        this.$message.success(res.msg)
                        this.getList()
                    })
                })
                .catch(() => {})
        },
        showColumn(prop) {
            const data = this.columns.find(c => c.prop === prop)
            return data?.visible ?? true
        },
        toSupply(url) {
            window.open(url, '_blank')
        },
        handleClick() {
            this.getList()
        },
        downloadExcel() {
            window.open(this.downloadUrl, '_blank')
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.published_time?.length == 2) {
                qyparams.published_time = [parseTime(qyparams.published_time[0], 'y-m-d'), parseTime(qyparams.published_time[1], 'y-m-d')]
            }
            qyparams.product_tag = qyparams.product_tag.join(',')
            exportProduct(qyparams)
                .then(res => {
                    console.log(res)
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },

        showProductDialog(row, type) {
            this.productDialog.visible = true
            this.productDialog.data = row
            this.productDialog.type = type
        },
        showSkuDialog(row, type) {
            this.skuDialog.visible = true
            this.skuDialog.data = row
            this.skuDialog.type = type
        },
        showSpuListDialog(row) {
            this.spuListDialog.visible = true
            this.spuListDialog.data = row
        },
        resetSort() {
            this.queryParams.spu_30days = undefined
            this.queryParams.spu_7days = undefined
            this.queryParams.spu_3days = undefined
        },
        handleSortChange({ column, prop, order }) {
            this.resetSort()
            if (prop === 'spu_30days') {
                this.queryParams[this.customDateKey] = order === 'descending' ? 'desc' : order === 'ascending' ? 'asc' : undefined
            } else {
                this.queryParams[prop] = order === 'descending' ? 'desc' : order === 'ascending' ? 'asc' : undefined
            }

            this.getList()
        },

        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.published_time?.length == 2) {
                qyparams.published_time = [parseTime(qyparams.published_time[0], 'y-m-d'), parseTime(qyparams.published_time[1], 'y-m-d')]
            }
            queryProductList(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 搜索按钮操作
        handleQuery2() {
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },
    },
}
</script>
<style>
.custom-select .el-select-dropdown__item {
    max-width: 450px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.border-cell {
    padding: 0 !important;
}
.border-cell .cell {
    padding: 0 !important;
}
.border-cell-item {
    padding: 10px;
    border-bottom: 1px solid #dfe6ec;
}
.border-cell-item:last-child {
    border-bottom: 0;
}
</style>
